from io import BytesIO
from urllib.parse import urlparse

import requests

from draw_img.visualize import visualize

_uri = 'http://192.168.5.233/v2/edoc/ocr/recognize/'
# _uri = 'http://127.0.0.1:7001/recognize/'
# _uri = 'http://192.168.5.51:7001/recognize/'
headers = {
    "Accept": "application/json",
    "Content-type": "application/json",
}


def get_page_dict(urls):
    """
    解析cos webp 图片提取坐标和旋转信息
    urls: url列表
    """
    page_dict = {}

    for uri in urls:
        parsed_url = urlparse(uri)
        # 提取不含参数的基础URL
        base_url = parsed_url.scheme + "://" + parsed_url.netloc + parsed_url.path
        query_list = parsed_url.query.split('|')
        rotate = ''
        cut = [0, 0, 0, 0]
        for _query in query_list:
            if _query.startswith('imageMogr2/rotate/'):
                rotate = f'?{_query}'
            elif _query.startswith('imageMogr2/cut/'):
                cut = [float(i) for i in _query[len('imageMogr2/cut/'):].split('x')]
        _data = {'uri': uri, 'query': parsed_url.query, 'str_rotate': rotate, 'cut': cut}
        page_dict.setdefault(base_url, []).append(_data)
    return page_dict


# {"data":["https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2802/img_22.webp?imageMogr2/cut/368.4695848140765x896.2773684666724x18.078256303090058x129.46228655629713",
# "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2802/img_22.webp?imageMogr2/cut/370.9592441709283x888.8083903961167x391.52715983087023x141.91058334055646"],"courseId":15156}
urls = [
    'https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2944/img_1.webp?imageMogr2/cut/1497.6883116883118x1216.0129870129867x134.65454541359628x853.8940038309469']
# urls = ['https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2802/img_22.webp?imageMogr2/cut/368.4695848140765x896.2773684666724x18.078256303090058x129.46228655629713']
urls = [
    'https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2944/img_1.webp?imageMogr2/cut/1497.6883116883118x1216.0129870129867x134.65454541359628x853.8940038309469'
]

# urls = [
#     "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2881/img_1.webp?imageMogr2/rotate/270|imageMogr2/cut/970.6592941071547x631.0887159706583x189.64696435502444x840.9267483628082",
#     "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2881/img_1.webp?imageMogr2/rotate/270|imageMogr2/cut/980.2697821676215x1332.6543443847404x1233.9866669257585x132.9541279084148"
# ]
#
urls = [
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_4.webp?imageMogr2/cut/685.5206311259861x381.4963597244256x40.16303340903658x658.8012257405518",
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_5.webp?imageMogr2/cut/683.2317475496055x669.498446091323x66.48519453741334x61.79985656227588"
]

urls = [
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2802/img_22.webp?imageMogr2/cut/363.0234183623477x881.8651076199496x26.853787091974688x146.58971229027685",
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/common/2024-06/2802/img_22.webp?imageMogr2/cut/354.73521246366397x881.8651076199496x399.82305253274285x146.58971229027685"]

urls = [
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_4.webp?imageMogr2/cut/685.5206311259861x381.4963597244256x40.16303340903658x658.8012257405518",
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_5.webp?imageMogr2/cut/683.2317475496055x669.498446091323x66.48519453741334x61.79985656227588"]

urls = [
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_1.webp?imageMogr2/cut/723.9728629579377x821.9541526815682x33.02332355188981x225.69192702986638",
    "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_2.webp?imageMogr2/cut/723.9728629579375x997.9575805184604x29.39438689545905x62.389777490481954"]

urls = [
    'https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2815/img_2.webp?imageMogr2/cut/813.6981114032991x1074.630839110686x5.306777759308511x22.888835763805883',
]
urls = [
        "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_2.webp?imageMogr2/cut/724x268x28x790",
        "https://demo-1251808174.cos.ap-chengdu.myqcloud.com/media/edoc/paper/2024-06/2958/img_3.webp?imageMogr2/cut/728x950x48x61"
    ]
page_dict = get_page_dict(urls)
img_list = []
for k, _data in page_dict.items():
    img_url = k + _data[0]['str_rotate']
    columns = [[i['cut'][2], i['cut'][3], i['cut'][0], i['cut'][1]] for i in _data]
    data = {'layout': {'column_count': 1,
                       'columns': columns},
            'urls': [img_url],
            }
    # print(data)
    params = {
        # 'det_limit_side_len': 960,
        'db_score_mode': 'slow',
        'db_box_thresh': 0.3,
        # 'db_unclip_ratio': 1.5,
        # 'db_thresh': 0.6,
        # 'det_use_dilation': True
    }
    x = requests.post(f'{_uri}', params=params, json=data, headers=headers)
    # print(x.content)
    content_json = x.json()
    print('content_json', content_json.keys())
    print('content_json.result', content_json['result'][0].keys())
    # =====获取image=====
    content = requests.get(img_url).content
    image_stream = BytesIO(content)
    pil_origin = visualize(image_stream)
    filteredBoxes = []
    dd = []
    for j in x.json()['result']:
        for i in j['result']:
            print(i)
            if i['box']:
                dd.append({'text': i['text'], 'box': i['box'], })
            else:
                pass
        for img_boxs in j['filteredBoxes']:
            print('img_boxs', img_boxs)
            pil_origin.add_line_box(img_boxs['bbox'], outline='#112233')
    print(dd)
    print('filteredBoxes', filteredBoxes)
    # dd = sorted(dd, key=lambda x: x['box'][1])
    # dd = get_lines(dd)

    for __box in columns:
        pil_origin.add_line_box(__box)

    num = 0
    for line in dd:
        num += 1
        # line.pop('img')
        print(num, line)
        box = line['box']
        pil_origin.add_box(box)
        pil_origin.add_order(box, num)
    img_list.append(pil_origin.get(isOrder=True))
pil_origin = None
for _img in img_list:
    if not pil_origin:
        pil_origin = _img
        continue
    pil_origin = visualize.createContrast(pil_origin, _img)
pil_origin.show()
print("可视化展示")
from pyvirtualdisplay import Display

disp = Display(visible=False, size=(1366, 768), manage_global_env=False)
disp.start()
disp.stop()


#  :param det_limit_side_len: 图片最大宽度
#         :param det_db_thresh: DB输出的概率图中，得分大于该阈值的像素点才会被认为是文字像素点
#         :param det_db_box_thresh: 检测结果边框内，所有像素点的平均得分大于该阈值时，该结果会被认为是文字区域
#         :param det_db_unclip_ratio: Vatti clipping算法的扩张系数，使用该方法对文字区域进行扩张
#         :param det_use_dilation: 是否对分割结果进行膨胀以获取更优检测效果
#         :param det_db_score_mode: DB的检测结果得分计算方法，支持fast和slow，fast是根据polygon的外接矩形边框内的所有像素计算平均得分，slow是根据原始polygon内的所有像素计算平均得分，计算速度相对较慢一些，但是更加准确一些。
#

#         db_thresh = request.args.get('db_thresh', 0.3)
#         db_box_thresh = request.args.get('db_box_thresh', 0.7)
#         db_unclip_ratio = request.args.get('db_unclip_ratio', 2)
#         db_score_mode = request.args.get('db_score_mode', 'slow')
#         self._batch_num = request.args.get('batch_num', 6)
#         """
# pprint(dict(url=_uri, json=data, headers=headers))


def get_lines(results):
    """
     result:
     {'box': [594, 51, 102, 63], 'clsScore': 0.9997661709785461, 'columnNum': 0, 'error': 0, 'lineNum': None,
     'pageNum': None, 'recScore': 0.9939430952072144, 'text': '索引', 'url': None},
    :param results: List[result]
    :return:List[List[result]]
    对ocr的数据按行分组，每行一个list
    """
    sorted_res = results
    # 用于存储归类后的识别结果
    grouped_res = []

    # 定义一个函数用于判断两个文本框的 y 坐标是否在同一行
    def is_same_line_and_non_overlapping_x(box1, box2, tolerance=5.5):
        # 计算两个文本框的y轴坐标范围
        y1_start, y1_end = box1[1], box1[1] + box1[3]
        y2_start, y2_end = box2[1], box2[1] + box2[3]
        # 判断两个范围是否有交集（即是否在同一行）
        # tolerance: 不同行y坐标会有少量交集，相交部分需要大于5.5,
        if (y1_start + tolerance <= y2_end) and (y2_start + tolerance <= y1_end):
            # # 检查X坐标是否不重合（或至少不接近）
            #
            # # 检查后一个文本在前一个文本之后
            # if x2_start + tolerance >= x1_end:
            return True

        return False

    # 将识别结果按行归类
    curr_line = []
    for _dict in sorted_res:
        if not curr_line:
            curr_line.append(_dict)
        else:
            # ocr排序有一定误差可能把第N的数据排到N+1行数据的后面 需要跨行找数据
            last_box = curr_line[-1]['box']
            if is_same_line_and_non_overlapping_x(last_box, _dict['box']):
                curr_line.append(_dict)
                continue
            elif len(grouped_res) >= 1:
                # 检查是否是上一行的数据
                last2_box = grouped_res[-1][0]['box']
                if is_same_line_and_non_overlapping_x(last2_box, _dict['box']):
                    grouped_res[-1].append(_dict)
                    continue
            elif len(grouped_res) >= 2:
                # 检查是否是上两行的数据
                last2_box = grouped_res[-2][0]['box']
                if is_same_line_and_non_overlapping_x(last2_box, _dict['box']):
                    grouped_res[-2].append(_dict)
                    continue
            grouped_res.append(curr_line)
            curr_line = [_dict]

    # 将最后一行加入到归类结果中
    lines = []
    if curr_line:
        grouped_res.append(curr_line)

    for _line in grouped_res:
        # 过滤空字符
        _line = filter(lambda x: x['text'] != '', _line)
        # 行内排序
        _line = sorted(_line, key=lambda x: x['box'][0])
        if not _line:
            continue
        # column_num = _line[0]['column_num']
        # page_num = _line[0]['page_num']
        left = min([c['box'][0] for c in _line])
        top = min([c['box'][1] for c in _line])
        width = max([c["box"][2] + c["box"][0] for c in _line]) - left
        height = max([c['box'][3] + c["box"][1] for c in _line]) - top
        new_boxes = [left, top, width, height]
        text = ''.join([c['text'] for c in _line])
        new_box_dict = {'box': new_boxes, 'text': text, }
        lines.append(new_box_dict)

    return lines
